<?php
/*
	Muffinz CMS - A website content management system.
	Copyright (C) 2010-2011 Sigitas Zelenkovas

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
	
	Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/

function rstrstr($haystack, $needle){ 
    return substr(strrev(strstr(strrev($haystack), strrev($needle))), 0, -strlen($needle)); 
}

function subval_sort($a, $subkey) {
	foreach($a as $k=>$v) {
		$b[$k] = strtolower($v[$subkey]); 
	}
	asort($b);
	foreach($b as $key=>$val) {
		$c[] = $a[$key];
	}
	return $c;
}

function checkemail($x){ 
	if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x)){
		return true;
	}else {
		return false;
	}
}

function to5md5($text){
	return md5(md5(md5(md5(md5($text)))));
}

function format_filesize($bytes){
	$labels = array(' B', ' KB', ' MB', ' GB', ' TB');
	foreach($labels AS $label){
		if($bytes > 1024){
			$bytes = $bytes / 1024;
		}else {
			break;
		}
	}
	return round($bytes, 3) . $label;
}

function generateRandomSring($length = 8, $case = 3){
	$string = "";
	$possible_string[1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	$possible_string[2] = "abcdefghijklmnopqrstuvwxyz1234567890";
	$possible_string[3] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
	$possible_string[4] = "1234567890";
	$possible_string[5] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$possible_string[6] = "abcdefghijklmnopqrstuvwxyz";
	$possible_string[7] = "0123456789abcdef";
	$i = 0;
	while ($i < $length){
		$char = substr($possible_string[$case], mt_rand(0, strlen($possible_string[$case])-1), 1);
		$string .= $char;
		$i++;
	}
	return $string;
}

function clamp($min, $max, $num){
	if($num >= $max){ return $max; }
	if($num <= $min){ return $min; }
	if($num >= $min && $num <= $max){ return $num; }
}

function time2Date($time){
	$hours = floor($time / 3600);
	$minuts = floor($time / 60 - $hours * 60);
	$seconds = floor($time - $hours * 3600 - $minuts * 60);
	
	if($hours < 10){ $hours = "0".$hours; }
	if($minuts < 10){ $minuts = "0".$minuts; }
	if($seconds < 10){ $seconds = "0".$seconds; }
	
	return array("h" => $hours, "m" => $minuts, "s" => $seconds);
}